<template>
  <div>
    <h5 class="need-title">规模信息</h5>
    <span>产品融资方案的规模详细内容</span>
    <el-tooltip placement="bottom" effect="light">
      <span class="ml-2 text-muted d-inline-block">
        <i class="fa fa-info-circle"></i>
      </span>
      <div slot="content">
        <p>一般以年为期限，核算每种产品的成本和收益，并根据投入规模计算授信额度</p>
        <div>例如：</div>
        <div>养猪，规模说明：生猪饲养，单位：头</div>
        <div class="pb-3">油茶，规模说明：种植油茶，单位：亩</div>
        <div>折旧期限：用于计算固定投入的一次性成本，以便估算融资需求；</div>
        <div>投入指标单价要按折旧期限折算成每期的单价</div>
      </div>
    </el-tooltip>
    <div class="card bg-light mb-4" v-loading="scaleLoading">
      <div class="card-body">
        <div class="d-flex" style="width: 86%">
          <div class="flex-1">
            <div class="text-muted">规模说明</div>
            <el-input
              placeholder="请填写"
              v-model="scaleInfo.scaleDesc"
              @blur="hanldeSaveInfo"
            ></el-input>
          </div>
          <div class="ml-2">
            <div class="text-muted">规模单位</div>
            <el-input
              placeholder="请填写"
              v-model="scaleInfo.scaleUnit"
              @blur="hanldeSaveInfo"
            ></el-input>
          </div>
          <div class="ml-2">
            <div class="text-muted">折旧期限</div>
            <el-input
              placeholder="请填写（单位自定）"
              v-model.number="scaleInfo.scalePeriod"
              type="number"
              @blur="hanldeSaveInfo"
            ></el-input>
          </div>
        </div>
      </div>
    </div>

    <h5 class="need-title">产品信息</h5>
    <span>与规模相关的可提供收入的产品信息</span>
    <el-tooltip placement="bottom" effect="light">
      <span class="ml-2 text-muted d-inline-block">
        <i class="fa fa-info-circle"></i>
      </span>
      <div slot="content">
        <div>例如：</div>
        <div>生猪饲养，产品为育肥猪</div>
        <div>种植油茶，产品为茶籽、茶油</div>
      </div>
    </el-tooltip>
    <div class="card bg-light mb-4" v-loading="productLoading">
      <div class="card-body">
        <table class="table table-sm table-borderless mb-0">
          <colgroup>
            <col width="25%" />
            <col width="15%" />
            <col width="15%" />
            <col width="15%" />
            <col width="16%" />
            <col width="14%" />
          </colgroup>
          <thead class="goods-credit-thead">
            <tr>
              <th class="font-weight-normal">产品名称</th>
              <th class="font-weight-normal">单价</th>
              <th class="font-weight-normal">单位</th>
              <th class="font-weight-normal">规模产出比</th>
              <th class="font-weight-normal">价格系数</th>
              <th class="font-weight-normal">操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(p, index) in products" :key="index">
              <td>
                <el-input
                  v-model="p.productName"
                  placeholder="请填写"
                  @blur="handleProductSave(index)"
                ></el-input>
              </td>
              <td>
                <el-input
                  v-model.number="p.unitPrice"
                  type="number"
                  placeholder="请填写"
                  @blur="handleProductSave(index)"
                ></el-input>
              </td>
              <td>
                <el-input
                  v-model="p.unit"
                  placeholder="请填写"
                  @blur="handleProductSave(index)"
                ></el-input>
              </td>
              <td>
                <el-input
                  v-model.number="p.unitScale"
                  type="number"
                  placeholder="请填写"
                  @blur="handleProductSave(index)"
                ></el-input>
              </td>
              <td>
                <el-input
                  v-model.number="p.coefficient"
                  type="number"
                  placeholder="请填写"
                  max="1"
                  min="0"
                  @blur="handleProductSave(index)"
                ></el-input>
              </td>
              <td>
                <el-button icon="el-icon-delete" @click="confirmDeleteProduct(index)"></el-button>
              </td>
            </tr>
            <tr>
              <td colspan="5">
                <el-button class="add-btn" icon="el-icon-plus" @click="handleProductAddRow">
                  添加产品
                </el-button>
              </td>
              <td></td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>

    <h5 class="need-title">投入指标</h5>
    <div>
      <span>从生产链上的各个节点测算客户实施该产品项目的需求金额</span>
      <el-tooltip effect="light" placement="bottom">
        <span class="ml-2 text-muted d-inline-block">
          <i class="fa fa-info-circle"></i>
        </span>
        <div slot="content">
          <p class="mb-0 font-weight-bold">计算公式：</p>
          <p class="mb-0">
            <span>
              资金需求 = ∑
              <sub>n</sub>
              (∑
              <sub>m</sub>
              (规模 * 产品规模产量 * 指标单价 * 指标系数))
            </span>
            <i class="ml-4">（n=指标数量，m=产品数量）</i>
          </p>
          <p class="mb-0 font-weight-bold mt-2">相关字段含义：</p>
          <p class="mb-0">· 产业链节点：产业链节点名称，如养殖、加工等</p>
          <p class="mb-0">· 指标：如基地、设备、人工等投入项目名称</p>
          <p class="mb-0">· 单价：单位产品投入单价</p>
          <p class="mb-0">· 系数：用于调节计算的系数，数值在0~1之间</p>
        </div>
      </el-tooltip>
    </div>
    <div class="card bg-light mb-4" v-loading="saveLoading">
      <div class="card-body">
        <div class="d-flex align-items-center">
          <div style="width: 18%" class="p-1">产业链节点</div>
          <div style="width: 25%" class="p-1">指标名</div>
          <div style="width: 18%" class="p-1">产品指标单价</div>
          <div style="width: 15%" class="p-1">价格系数</div>
          <div style="width: 10%" class="p-1">是否为固定投入</div>
          <div style="width: 14%" class="p-1">操作</div>
        </div>
        <hr class="my-0" />
        <div v-for="(p, index) in indexProducts" :key="index">
          <div class="p-1 font-weight-bold">{{ p.productName }}</div>
          <table class="table table-sm table-borderless mb-0">
            <colgroup>
              <col width="18%" />
              <col width="25%" />
              <col width="18%" />
              <col width="15%" />
              <col width="10%" />
              <col width="14%" />
            </colgroup>
            <draggable v-model="p.indexes" tag="tbody" handle=".mover">
              <tr v-for="(item, serial) in p.indexes" :key="serial">
                <td>
                  <el-autocomplete
                    v-model="item.chainName"
                    :fetch-suggestions="chainQuerySearch"
                    placeholder="请填写"
                    @blur="handleIndexSave(p, item, serial)"
                  ></el-autocomplete>
                </td>
                <td>
                  <el-input
                    v-model="item.indexName"
                    placeholder="请填写"
                    @blur="handleIndexSave(p, item, serial)"
                  ></el-input>
                </td>
                <td>
                  <el-input
                    v-model.number="item.unitPrice"
                    placeholder="请填写"
                    type="number"
                    @blur="handleIndexSave(p, item, serial)"
                  ></el-input>
                </td>
                <td>
                  <el-input
                    v-model.number="item.coefficient"
                    placeholder="请填写"
                    type="number"
                    max="1"
                    min="0"
                    @blur="handleIndexSave(p, item, serial)"
                  ></el-input>
                </td>
                <td>
                  <div class="pt-1 text-center">
                    <el-switch
                      :width="30"
                      v-model="item.isFixedInvest"
                      :active-value="1"
                      :inactive-value="0"
                      @change="handleIndexSave(p, item, serial)"
                    ></el-switch>
                  </div>
                </td>
                <td class="text-center">
                  <el-button
                    icon="el-icon-delete"
                    @click="confirmDeleteIndex(p.indexes, index)"
                  ></el-button>
                  <el-tooltip effect="light" content="上下拖动可以排序" placement="right">
                    <el-button icon="el-icon-sort mover"></el-button>
                  </el-tooltip>
                </td>
              </tr>
            </draggable>
            <tr>
              <td colspan="4">
                <el-button class="add-btn" icon="el-icon-plus" @click="addIndex(p)">
                  添加指标
                </el-button>
              </td>
              <td></td>
            </tr>
          </table>
        </div>
      </div>
    </div>

    <h5 class="need-title">授信额度</h5>
    <div>
      <span>对客户的风险和财务状况进行综合评估的基础上，确定客户最高风险控制承受能力</span>
      <el-tooltip effect="light" placement="bottom">
        <span class="ml-2 text-muted d-inline-block">
          <i class="fa fa-info-circle"></i>
        </span>
        <div slot="content">
          <p class="mb-0 font-weight-bold">计算公式：</p>
          <p class="mb-0">
            <span>
              授信额度 = ∑
              <sub>n</sub>
              (规模 * 产品规模产量 * 产品单价 * 价格系数 * 折旧期限(如果为固定投入)) - 负债
            </span>
            <i class="ml-4">（n=产品数量）</i>
          </p>
        </div>
      </el-tooltip>
    </div>

    <div class="mt-3">
      <el-button class="btn-long" style="width: 86%" type="primary" plain @click="handleCalcShow">
        <span>去测算</span>
        &nbsp;
        <i class="fa fa-angle-double-right"></i>
      </el-button>
    </div>

    <goods-credit-need-calc-dialog
      :visible.sync="calcVisible"
      :goods-id="goodsId"
    ></goods-credit-need-calc-dialog>
  </div>
</template>

<script>
import draggable from 'vuedraggable'
import {
  getInfo,
  putInfo,
  getStoreByGoodsId,
  addStore,
  updateStore,
  deleteStore,
  getProduct,
  addProduct,
  updateProduct,
  deleteProduct,
} from '@/credit/views/province/goods/goodsStore'

import GoodsCreditNeedCalcDialog from '@/credit/views/province/goods/GoodsCreditNeedCalcDialog'

const emptyInfo = { scaleDesc: '', scaleUnit: '', scalePeriod: 1 }
const emptyIndex = { chainName: '', indexName: '', unitPrice: '', coefficient: '' }
const emptyProduct = {
  productName: '',
  unitPrice: '',
  unit: '',
  unitScale: '',
  coefficient: '',
  indexes: [{ ...emptyIndex }],
}

export default {
  components: {
    draggable,
    GoodsCreditNeedCalcDialog,
  },
  props: {
    goodsId: {
      type: String,
      require: true,
    },
  },
  data() {
    return {
      loading: false,

      // 规模信息
      scaleLoading: false,
      scaleInfo: {
        ...emptyInfo,
      },

      // 产品
      productLoading: false,
      products: [],

      // 指标
      saveLoading: false,

      calcVisible: false,
    }
  },
  computed: {
    enumChains() {
      const strs = []
      for (const p of this.products) {
        for (const index of p.indexes) {
          strs.push(index.chainName)
        }
      }
      return [...new Set(strs)].map(it => ({ value: it }))
    },
    indexProducts() {
      return this.products.filter(p => p.id)
    },
  },
  watch: {
    goodsId: {
      handler: function () {
        this.getInfo()
        this.getProduct()
      },
      immediate: true,
    },
  },
  created() {},
  mounted() {},
  methods: {
    addIndex(p) {
      p.indexes.push({ ...emptyIndex })
    },
    confirmDeleteIndex(indexes, index) {
      if (!indexes[index].id) {
        return indexes.splice(index, 1)
      }

      this.$utils
        .msgbox({
          message: '是否删除该指标？',
          type: 'warning',
          beforeClose: () => this.deleteIndex(indexes, index),
        })
        .then(() => {
          //
        })
        .catch(() => this.$message.error(`删除失败，请重试！`))
    },
    deleteIndex(indexes, index) {
      this.saveLoading = true
      return deleteStore(indexes[index].id).finally(() => {
        this.saveLoading = false
      })
    },
    chainQuerySearch(queryString, cb) {
      if (!queryString) {
        return cb(this.enumChains)
      }
      const result = this.enumChains.filter(it => it.value.includes(queryString))
      cb(result)
    },
    handleIndexSave(p, item, index) {
      const { id, indexName, chainName, unitPrice, coefficient, isFixedInvest } = item
      if (!indexName) return

      const data = {
        indexName,
        chainName,
        unitPrice,
        coefficient,
        goodsId: this.goodsId,
        productId: p.id,
        order: index,
        isFixedInvest,
      }
      if (id) {
        updateStore(id, data)
      } else {
        addStore(data)
          .then(id => {
            item.id = id
          })
          .catch(() => {
            this.$message.error('保存指标失败！')
          })
      }
    },

    // 规模
    getInfo() {
      if (!this.goodsId) return

      this.scaleLoading = true
      getInfo(this.goodsId)
        .then(res => {
          this.scaleInfo = res || { ...emptyInfo }
        })
        .catch(() => {
          this.$message.error('获取规模信息失败')
        })
        .finally(() => {
          this.scaleLoading = false
        })
    },
    hanldeSaveInfo() {
      if (!this.scaleInfo.scaleDesc || !this.scaleInfo.scaleUnit || !this.scaleInfo.scalePeriod)
        return
      putInfo(this.goodsId, this.scaleInfo).catch(() => {
        this.$message.error('保存规模信息失败')
      })
    },

    // 产品
    getProduct() {
      if (!this.goodsId) return
      this.productLoading = true
      Promise.all([getProduct(this.goodsId), getStoreByGoodsId(this.goodsId)])
        .then(([products, stores]) => {
          const ps = products || []
          this.addEmptyProduct(1, this.products.length)

          const indexes = {}
          for (const index of stores) {
            if (!indexes[index.productId]) {
              indexes[index.productId] = [{ ...index }]
            } else {
              indexes[index.productId].push({ ...index })
            }
          }

          for (const product of ps) {
            let pi = indexes[product.id] || []
            if (!pi.length) {
              pi = [{ ...emptyIndex }]
            }
            product.indexes = pi
          }
          this.products = ps
        })
        .catch(() => {
          this.$message.error('获取产品信息失败')
        })
        .finally(() => {
          this.productLoading = false
        })
    },
    addEmptyProduct(len, currentLen) {
      for (let i = currentLen; i < len; i++) {
        this.products.push({ ...emptyProduct })
      }
    },
    handleProductSave(index) {
      const { id, productName, unitPrice, unit, unitScale, coefficient } = this.products[index]

      if (productName && unitPrice && unit && unitScale && coefficient) {
        const data = {
          productName,
          unitPrice,
          unit,
          unitScale,
          coefficient,
          goodsId: this.goodsId,
        }
        if (id) {
          updateProduct(id, data)
        } else {
          addProduct(data)
            .then(() => {
              this.getProduct()
            })
            .catch(() => {
              this.$message.error('保存产品信息失败！')
            })
        }
      }
    },
    handleProductAddRow() {
      this.products.push({ ...emptyProduct })
    },
    confirmDeleteProduct(index) {
      const { id } = this.products[index]
      if (!id) {
        return this.products.splice(index, 1)
      }

      this.$utils
        .msgbox({
          message: '是否删除该产品？',
          type: 'warning',
          beforeClose: () => deleteProduct(id),
        })
        .then(() => {
          this.products.splice(index, 1)
        })
        .catch(() => this.$message.error(`删除失败，请重试！`))
    },

    // 测算
    handleCalcShow() {
      this.calcVisible = true
    },
  },
}
</script>

<style lang="scss" scoped>
/deep/ .el-input input[type='number'] {
  padding-right: 0;
}
.add-btn {
  width: 100%;
  border-style: dashed;
  border-color: var(--primary-light-6);
  color: var(--primary);
}
.goods-credit-thead {
  color: var(--secondary);
}
.need-title {
  font-weight: bold;
  font-size: 1.15rem;
  margin-bottom: 0;
}
.need-desc {
  padding: 0.25rem;
  margin-bottom: 0.5rem;
}
</style>
